package org.kfive.nova.io.nio;

import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: admin
 * Date: 16-5-15
 * Time: 上午11:28
 * To change this template use File | Settings | File Templates.
 */
public class NioServer {

    private Selector selector;

    public void initServer(int port) throws IOException{
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(port));
        this.selector = Selector.open();
        serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
    }

    public void listen() throws IOException{
        while (true){
            this.selector.select();
            Iterator iterator= this.selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = (SelectionKey)iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel)key.channel();
                    SocketChannel channel = server.accept();
                    channel.configureBlocking(false);
                    channel.write(ByteBuffer.wrap(new String("hello client").getBytes()));
                    channel.register(this.selector,SelectionKey.OP_READ);
                }else if(key.isReadable()){
                    SocketChannel channel = (SocketChannel)key.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    channel.read(byteBuffer);
                    byteBuffer.flip();
                    byte [] data = new byte[byteBuffer.remaining()];
                    byteBuffer.get(data);
                    String msg =  new String(data);
                    System.out.println("server receiver clent msg:"+msg);
                    byteBuffer.remaining();
                    channel.write(byteBuffer);
                }
            }
        }
    }

    public static void main(String[] args) {

        NioServer server = new NioServer();
        try {
            server.initServer(9090);
            server.listen();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

}
